﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Commerce.Common;
using umbraco.cms.businesslogic.member;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class OrdersToItemsXML : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int filter = int.Parse(Request["f"]);
            DateTime startDateParam = DateTime.Parse(Request["sd"]);
            DateTime endDateParam = DateTime.Parse(Request["ed"]);

            // get collection values
            Commerce.Common.OrderCollection orders = null;

            //Assemble start and end dates.

            DateTime startDate;
            DateTime endDate = DateTime.Now;

            int year = DateTime.Today.Year;
            int month = DateTime.Today.Month;
            int day = DateTime.Today.Day;


            switch (filter)
            {
                case 1: // Yesterday
                    startDate = new DateTime(year, month, day).AddDays(-1);
                    endDate = new DateTime(year, month, day, 23, 59, 59).AddDays(-1);

                    break;

                case 2: //This week from Monday

                    DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
                    int daysOffset = dayOfWeek - DayOfWeek.Monday;
                    DateTime start = DateTime.Now.AddDays(-daysOffset);

                    startDate = new DateTime(start.Year, start.Month, start.Day);
                    endDate = new DateTime(year, month, day, 23, 59, 59);
                    break;

                case 3: //This month
                    startDate = new DateTime(year, month, 1);
                    endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month), 23, 59, 59);
                    break;

                case 4: //Custom dates
                    startDate = startDateParam;
                    endDate = endDateParam;
                    break;

                default: // Today
                    startDate = new DateTime(year, month, day);
                    endDate = new DateTime(year, month, day, 23, 59, 59);

                    break;
            }

            //var orderItems = SPs.OrderCSVDump(startDate, endDate).GetReader();

            orders = new OrderCollection().Where("orderStatusID", SubSonic.Comparison.NotEquals, OrderStatus.NotProcessed).Where(Order.Columns.OrderDate, SubSonic.Comparison.GreaterOrEquals, startDate).Where(Order.Columns.OrderDate, SubSonic.Comparison.LessOrEquals, endDate).OrderByDesc("OrderDate").Load();

            XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);

            textWriter.WriteStartDocument();

            // Write comments
            textWriter.WriteComment(string.Format("Order Items from {0} to {1}",startDate.ToShortDateString(),endDate.ToShortDateString()));
            textWriter.WriteComment("myXmlFile.xml in root dir");


            textWriter.WriteEndDocument();

            textWriter.Close();  

            //StringBuilder csv = new StringBuilder();

            //var line = new StringBuilder();

            //// Header
            //line.AppendFormat("Order Date");
            //line.AppendFormat(",Order Status");
            //line.AppendFormat(",Order Number");
            //line.AppendFormat(",Username");
            //line.AppendFormat(",First Name");
            //line.AppendFormat(",Last Name");
            //line.AppendFormat(",Email");
            //line.AppendFormat(",SKU");
            //line.AppendFormat(",Product Name");
            //line.AppendFormat(",Quantity");
            //line.AppendFormat(",Original Price");
            //line.AppendFormat(",Price Paid");
            //line.AppendFormat(",Subtotal Amount");
            //line.AppendFormat(",Shipping Amount");
            //line.AppendFormat(",Discount Amount");
            //line.AppendFormat(",Shipping Method");

            //line.AppendFormat("\"Order Date\"");
            //line.AppendFormat(",\"Order Status\"");
            //line.AppendFormat(",\"Order Number\"");
            //line.AppendFormat(",\"Username\"");
            //line.AppendFormat(",\"First Name\"");
            //line.AppendFormat(",\"Last Name\"");
            //line.AppendFormat(",\"Email\"");
            //line.AppendFormat(",\"SKU\"");
            //line.AppendFormat(",\"Product Name\"");
            //line.AppendFormat(",\"Quantity\"");
            //line.AppendFormat(",\"Original Price\"");
            //line.AppendFormat(",\"Price Paid\"");
            //line.AppendFormat(",\"Subtotal Amount\"");
            //line.AppendFormat(",\"Shipping Amount\"");
            //line.AppendFormat(",\"Discount Amount\"");
            //line.AppendFormat(",\"Shipping Method\"");

            //csv.AppendLine(line.ToString());

            // Data
            //foreach (var order in orders)
            //{
            //    OrderItemCollection orderItems =
            //          new OrderItemCollection().Where(OrderItem.Columns.OrderID, SubSonic.Comparison.Equals, order.OrderID).Load();

            //    if (orderItems == null)
            //    {
            //        csv.AppendLine("*** ERROR *** No item details for order #" + order.OrderNumber);
            //        continue;
            //    }

            //    foreach (var orderItem in orderItems)
            //    {
            //        StringBuilder orderDetailsLine = new StringBuilder();

            //        orderDetailsLine.AppendFormat("\"{0} {1}\"", order.OrderDate, order.OrderStatus);

            //        // ROB: adding the business name, if available, to the order details output...
            //        //Member[] thisMember = Member.GetMemberByName(order.UserName, false);
            //        ////System.Web.Security.MembershipUserCollection thisMember = System.Web.Security.Membership.FindUsersByName(order.UserName);
            //        //string businessName = "";
            //        //if (thisMember.Length > 0)
            //        //{

            //        //    if (thisMember[0].getProperty("businessName") != null)
            //        //    {
            //        //        businessName = thisMember[0].getProperty("businessName").Value.ToString();
            //        //    }
            //        //}

            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.OrderNumber);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.UserName);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.OrderStatus);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.FirstName);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.LastName);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.Sku);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.ProductName);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.Quantity);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.OriginalPrice);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", orderItem.PricePaid);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.SubTotalAmount);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.ShippingAmount);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.DiscountAmount);
            //        orderDetailsLine.AppendFormat(",\"{0}\"", order.ShippingMethod);

            //        csv.AppendLine(orderDetailsLine.ToString());
            //    }
            //}

            //string attachment = "attachment; filename=OrderDetails.csv";
            //HttpContext.Current.Response.Clear();
            //HttpContext.Current.Response.ClearHeaders();
            //HttpContext.Current.Response.ClearContent();
            //HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            //HttpContext.Current.Response.ContentType = "text/csv";
            //HttpContext.Current.Response.AddHeader("Pragma", "public");

            //HttpContext.Current.Response.Write(csv.ToString());

            //HttpContext.Current.Response.End();
        }
    }
}